package com.bbcare.nutritious.plat.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bbcare.comm.AppException;
import com.bbcare.comm.Constants;
import com.bbcare.comm.DateUtil;
import com.bbcare.comm.ErrorCode;
import com.bbcare.comm.ToolUtils;
import com.bbcare.comm.QueryModel;
import com.bbcare.comm.ResultModel;
import com.bbcare.nutritious.plat.service.IActivityHuamiService;

/**
 *
 * @name:         ActivityHuamiController.java
 * @author:       tao
 * @createTime:   2017年11月6日
 * @description:  手环运动控制器    --无会话接口
 * @modify:
 *
 */
@Controller
@RequestMapping("/service/nutrition")
public class ActivityHuamiController {

    public static final Logger logger = Logger.getLogger(ActivityHuamiController.class);

    @Autowired
    private IActivityHuamiService activityHuamiService;

    //华米手环授权列表
    @ResponseBody
    @RequestMapping("/authorization/list")
    public Map<String, Object> getPatientAuthorizationList(HttpServletRequest request, @RequestBody String jsonStr)
            throws Exception {
        logger.info("in authorizationList----arg==" + jsonStr);
        JSONObject jsonEsb = JSON.parseObject(jsonStr);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }

        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        String authorId = (String) sessionMap.get("authorId");// 创建人
        requestParam.put("tenantId",tenantId);
        requestParam.put("authorId",authorId);

        String jsonargs = requestParam.getString(Constants.INF_INPUTPARAM_DATATABLE_FIELD);
        int draw = 0;
        if (!StringUtils.isEmpty(jsonargs)){
            JSONObject jsonTable = (JSONObject) JSONObject.parse(jsonargs);
            draw = jsonTable.getIntValue("draw");
            requestParam.put("page", jsonTable.getIntValue("start"));
            requestParam.put("rows", jsonTable.getIntValue("length"));
        }

        List<Map<String,Object>> list = activityHuamiService.getPatientAuthorizationList(requestParam);
        int total = 0;
		if(!CollectionUtils.isEmpty(list)){
			total = activityHuamiService.getPatientAuthorizationCount(requestParam);
		}

        Map<String, Object> retMap = new HashMap<String, Object>();
        retMap.put("draw", draw);
        retMap.put("recordsTotal", total);
        retMap.put("recordsFiltered", total);
        retMap.put("rows",list);
        logger.debug("out authorizationList----arg==");
		return retMap;
    }

    //华米手环步数数据用列表
    @ResponseBody
    @RequestMapping("/activities/patientListqry")
    public QueryModel<Map<String, Object>> getActivityPatientList(HttpServletRequest request, @RequestBody String jsonStr)
            throws Exception {
        logger.info("in getActivityPatientList----arg==" + jsonStr);
        JSONObject jsonEsb = JSON.parseObject(jsonStr);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }

        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        String authorId = (String) sessionMap.get("authorId");// 创建人
        requestParam.put("tenantId",tenantId);
        requestParam.put("authorId",authorId);

        List<Map<String,Object>> list = activityHuamiService.getActivityPatientList(requestParam);
        int total = 0;
		if(!CollectionUtils.isEmpty(list)){
			total = activityHuamiService.getActivityPatientCount(requestParam);
		}
        logger.debug("out getActivityPatientList----arg==");
        return new QueryModel<Map<String, Object>>(list,total);
    }

    //华米手环睡眠数据用户列表
    @ResponseBody
    @RequestMapping("/sleep/patientListqry")
    public QueryModel<Map<String, Object>> getSleepPatientList(HttpServletRequest request, @RequestBody String jsonStr)
            throws Exception {
        logger.info("in getSleepPatientList----arg==" + jsonStr);
        JSONObject jsonEsb = JSON.parseObject(jsonStr);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }

        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        String authorId = (String) sessionMap.get("authorId");// 创建人
        requestParam.put("tenantId",tenantId);
        requestParam.put("authorId",authorId);

        List<Map<String,Object>> list = activityHuamiService.getSleepPatientList(requestParam);
        int total = 0;
		if(!CollectionUtils.isEmpty(list)){
			total = activityHuamiService.getSleepPatientCount(requestParam);
		}
        logger.debug("out getSleepPatientList----arg==");
        return new QueryModel<Map<String, Object>>(list,total);
    }

    @ResponseBody
    @RequestMapping("/activities/list")
    public ResultModel<Object> getActivityListByUserId(@RequestBody String arg,
            HttpServletRequest request) throws Exception {
    	logger.info("in getActivityListByUserId----arg==" + arg);
        JSONObject jsonEsb = JSON.parseObject(arg);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
		if(null == requestParam ){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}
        String userId = requestParam.getString("userId");
        if(StringUtils.isEmpty(userId)){
        	logger.debug("out getActivityListByUserId----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，患者ID不能为空");
        }
        Map<String, Object> paramMap = new HashMap<String, Object>();


        String startTime = requestParam.getString("startTime");
		//上传开始时间和 上传结束时间 校验
		if(!StringUtils.isEmpty(startTime) && !DateUtil.isValidDate(startTime,DateUtil.FORMAT_DAY)){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "开始时间格式不正确");
		}
		String endTime = requestParam.getString("endTime");

		if(!StringUtils.isEmpty(endTime) && !DateUtil.isValidDate(endTime,DateUtil.FORMAT_DAY)){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "结束格式不正确");
		}

        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        paramMap.put("tenantId",tenantId);
        paramMap.put("userId",userId);

        paramMap.put("type",Constants.HUAMI_TYPE_ACTIVITIES);
        paramMap.putAll(requestParam);
        Map<String, Object> map= activityHuamiService.getHuamiDataListByUserId(paramMap);
        /*if(!CollectionUtils.isEmpty(list)){
        	familyReportService.getGrowthPatientCount(paramMap);
        }*/
		logger.info("out getActivityListByUserId----arg==" + map);
		return new ResultModel<Object>(map);
    }

    @ResponseBody
    @RequestMapping("/sleep/list")
    public ResultModel<Object> getSleepListByUserId(@RequestBody String arg,
            HttpServletRequest request) throws Exception {
    	logger.info("in getSleepListByUserId----arg==" + arg);
        JSONObject jsonEsb = JSON.parseObject(arg);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
		if(null == requestParam ){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}
        String userId = requestParam.getString("userId");
        if(StringUtils.isEmpty(userId)){
        	logger.debug("out getSleepListByUserId----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，患者ID不能为空");
        }
        Map<String, Object> paramMap = new HashMap<String, Object>();


        String startTime = requestParam.getString("startTime");
		//上传开始时间和 上传结束时间 校验
		if(!StringUtils.isEmpty(startTime) && !DateUtil.isValidDate(startTime,DateUtil.FORMAT_DAY)){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "开始时间格式不正确");
		}
		String endTime = requestParam.getString("endTime");

		if(!StringUtils.isEmpty(endTime) && !DateUtil.isValidDate(endTime,DateUtil.FORMAT_DAY)){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "结束格式不正确");
		}

        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        paramMap.put("tenantId",tenantId);
        paramMap.put("userId",userId);
        paramMap.put("type",Constants.HUAMI_TYPE_SLEEP);
        paramMap.putAll(requestParam);
        Map<String, Object> map= activityHuamiService.getHuamiDataListByUserId(paramMap);
        /*if(!CollectionUtils.isEmpty(list)){
        	familyReportService.getGrowthPatientCount(paramMap);
        }*/
		logger.info("out getSleepListByUserId----arg==" + map);
		return new ResultModel<Object>(map);
    }

    @ResponseBody
    @RequestMapping("/authorization/geturl")
    public ResultModel<Object> getGetAuthUrl(@RequestBody String arg,
            HttpServletRequest request) throws Exception {
    	logger.info("in getGetAuthUrl----arg==" + arg);
        JSONObject jsonEsb = JSON.parseObject(arg);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
		if(null == requestParam ){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}
        String userId = requestParam.getString("userId");
        if(StringUtils.isEmpty(userId)){
        	logger.debug("out getGetAuthUrl----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，患者ID不能为空");
        }
        Map<String, Object> paramMap = new HashMap<String, Object>();

        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        paramMap.put("tenantId",tenantId);
        paramMap.put("userId",userId);
        paramMap.putAll(requestParam);
        Map<String, Object> map= activityHuamiService.getHuamiAuthUrl(paramMap);
        /*if(!CollectionUtils.isEmpty(list)){
        	familyReportService.getGrowthPatientCount(paramMap);
        }*/
		logger.info("out getGetAuthUrl----arg==" + map);
		return new ResultModel<Object>(map);
    }

}
